<?php
namespace App\Http\Controllers\Pc;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;


class LoginController extends Controller{
////////////////////////////////////////////////  登录
	/**
	 * 登录
	 * @param account 账号
	 * @param password 密码
	 */
	public function login(Request $request){
		//验证参数
		$this->validate($request, [
			'account' => 'required| string',
			'password' => 'required| string',
		], [
			'account.required' => '请输入账号',
			'account.string' => 'account必须是字符串',
			'password.required' => '请输入密码',
			'password.string' => 'password必须字符串',
		]);
		
		$data = $request->all();

		$call_login = new  \App\Libs\wrapper\Login();
		$return = $call_login->login($data);
        if (!isset($return['Id'])){
            $this->back('登录失败！'.$return, '500');
        }
		$om_name = '';
		$om_id = 0;
		$organize = db::table('organizes_member')->where('user_id',$return['Id'])->first();
		if($organize){
			$organize_id = $organize->organize_id;
			$om = db::table('organizes')->where('Id',$organize_id)->first();
            if (!empty($om)){
                if($om->fid>0){
                    $om = db::table('organizes')->where('Id',$om->fid)->first();
                }
            }

			$om_name = $om->name ?? '';
			$om_id = $om->Id ?? 0;
		}
		 
		$return['om_name'] = $om_name;
		$return['om_id'] = $om_id;


		$log['ip'] =$request->getClientIp()??0;
		$log['user_id'] = $return['Id'];
		$log['login_time'] = date('Y-m-d H:i:s',time());
		db::table('user_login_log')->insert($log);
		
		if(is_array($return)){
			$this->back('登录成功', '200', $return);
		}else{
			$this->back($return);
		}
	}
	
	/**
	 * 自动登录
	 * @param account 账号
	 */
	public function login_zd(Request $request){
		//验证参数
		$this->validate($request, [
			'account' => 'required| string',
		], [
			'account.required' => 'account为空',
			'account.string' => 'account必须是字符串',
		]);
		
		$data = $request->all();
		$call_login = new  \App\Libs\wrapper\Login();
		$return = $call_login->login_zd($data);
//		var_dump($return);exit;
		if(is_array($return)){
			$this->back('登录成功', '200', $return);
		}else{
			$this->back($return);
		}
	}
	
	/**
	 * 注册
	 * @parma account 账号
	 * @param password 密码
	 * @paran phone 联系电话
	 */
	public function register(Request $request){
		$this->validate($request, [
			'account' => 'required| string',
			'password' => 'required| string',
			'phone' => 'required| string',
		], [
			'account.required' => '请填写账号',
			'account.string' => 'account必须是字符串',
			'password.required' => '请填写登录密码',
			'password.string' => 'password必须是字符串',
			'phone.required' => 'phone为空',
			'phone.string' => 'phone必须是字符串',
		]);
		
		$data = $request->all();
		$call_login = new  \App\Libs\wrapper\Login();
		$return = $call_login->register($data);
//		var_dump($return);exit;
		if($return === 1) {
			$this->back('注册成功', '200');
		}else{
			$this->back($return);
		}
	}
	
	
	
	
	
	
	
	
	
	/**
	 * Api调用--测试
	 * http://www.admin.com:84/pc/login/api_test
	 */
	public function api_test(){
		$arr = array('39982.78', '159641.98', '0', '0', '0', '0', '0', '0', '0', '206751.33', '281.22');
		
		$sum = array_sum($arr);//406826.71  406657.31
		var_dump($sum);exit;
		
		
		
		$time = time();
		$nonce = $this->nonce();
		$arr = array();
		$arr['appid'] = 'F978F65393E7632EC73AC9D444BC5200';//onedog系统提供
		$arr['secretkey'] = 'AF4A5140C254D021145258CEEA5C7266';//onedog系统提供
		$arr['method'] = 'exploit_add';//调用方法名
		$arr['nonce'] = $nonce;//随机字符串
		$arr['timestamp'] = $time;//时间戳
		$sign = $this->sign($arr);
		
		$arr = array();
		$arr['id_three'] = 2;//唯一标识（由客户提供）
		$arr['founder'] = '张三';//创建人
		$arr['style_no'] = '20190317';//款号
		$arr['style_desc'] = '秋季男士卫衣';//款式描述
		$arr['img'] = 'http://q61nhbqyj.bkt.clouddn.com/20200306_E9658A5C262A377862F224539D9322CD.png';//产品款式图
		$arr['color_set'] = '黄/红/蓝';//色组
		$arr['fabric'] = '棉麻';//面料
		$arr['accessories'] = '尼龙';//辅料
		$arr['sample_size'] = 'S/M/L';//打样尺码
		$arr['suggestion'] = '修改意见';//修改意见
		$arr['reference_size'] = 'http://q61nhbqyj.bkt.clouddn.com/20200306_E9658A5C262A377862F224539D9322CD.png';//参考尺寸（文件路径）
		$arr['number_yj'] = 500;//预计下单数量
		$arr['time_yixd'] = '2020-04-17';//大货预计下单时间
		$arr['img_list'] = 'http://q61nhbqyj.bkt.clouddn.com/20200306_E9658A5C262A377862F224539D9322CD.png,http://q61nhbqyj.bkt.clouddn.com/20200306_025527FDDAB259DA6114A5AF3E407E6E.png';//产品细节图
		
		$arr['nonce'] = $nonce;//随机字符串
		$arr['timestamp'] = $time;//当前时间戳
		$arr['sign'] = $sign;//签名
		
		
		/*$keyword = urlencode($_POST['keyword']);
		$parameters = json_encode(array('keyWord'=>$keyword,'areaCode'=>'*'));
		$post_data['appToken'] = "323ds7674354fds32fdsda60173";//随便写的
		$post_data['parameters'] = $parameters;*/
		
		
		$url = 'http://www.xiong.com:86/api/exploit/exploit_add';//随便写的
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);//用post方法传送参数
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$response = curl_exec($ch);
		curl_close($ch);
		
		$aa = json_decode($response, true);
		var_dump($aa);
		
	}
	
	/**
	 * 生成验签
	 * @param $data（验签数据）
	 */
	public function sign($data){
		//第一步：参数名ASCII码从小到大排序（字典序）
		ksort($data);
		
		$string = '';
		foreach ($data as $k => $v){
			if($k != "sign" && $v != "" && !is_array($v)){
				$string .= $k . "=" . $v . "&";
			}
		}
		
		$string = trim($string, "&");
		$sign = md5($string);
		return $sign;
	}
	
	//生成随机数
	public function nonce( $length = 8 ){
	
		// 密码字符集，可任意添加你需要的字符
		$chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
			'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
			't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
			'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
			'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
			'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!',
			'@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_',
			'[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',',
			'.', ';', ':', '/', '?', '|');
		// 在 $chars 中随机取 $length 个数组元素键名
		$keys = array_rand($chars, $length);
		$password = '';
		for($i = 0; $i < $length; $i++)
		{
			// 将 $length 个数组元素连接成字符串
			$password .= $chars[$keys[$i]];
		}
		return $password;
	}
  
  
	
	/**
	 * 订单超期提醒
	 * @login 订单超期(时间节点)  周一、周三早上9点给业务员、跟单员  发送邮件
	 *  实际时间未填写并且当前时间大于预期时间，发送邮件提醒
		实际时间有填写，不发送邮件
	 */
	public function overdue_remind_1(){
		//获取用户
		$sql = "select `Id`, `email`, `name`
						from users
						where state=1 and email!=''
						limit 4";
		$user_list = json_decode(json_encode(db::select($sql)),true);
		
		//发送邮件
		$sending_num = 0;
		$mail = new \App\Libs\PHPMailer\src\PHPMailer();//实例化邮箱
		
		$email_list = array();
		
		foreach ($user_list as $ka=>$va){
			//用户相关订单
			$sql = "select od.order_no, od.style_no, odn.*
					from orders_detailed od
					inner join orders_detailed_node odn on odn.detailed_id = od.Id
					where od.file_state=1 and (od.user_yw={$va['Id']} or od.user_gd={$va['Id']})";
			$order_list = json_decode(json_encode(db::select($sql)),true);
			if(empty($order_list)){
				//无相关订单
				continue;
			}
			
			//获取超期订单
			$overdue_order = '';
			foreach ($order_list as $k=>$v){
				//判断是不是超期订单
				$state = '';
				if($v['head_mail_sj'] == '' && strtotime($v['head_mail_yq']) < time()) {
					$state = '头样寄出已超期';
				}
				if($v['head_time_sj'] == '' && strtotime($v['head_time_yq']) < time()) {
					$state = '头样意见已超期';
				}
				if($v['contract_sj'] == '' && strtotime($v['contract_yq']) < time()) {
					$state = '下合同已超期';
				}
				if($v['card_mail_sj'] == '' && strtotime($v['card_mail_yq']) < time()) {
					$state = '色卡寄出已超期';
				}
				if($v['card_opinion_sj'] == '' && strtotime($v['card_opinion_yq']) < time()) {
					$state = '色卡意见已超期';
				}
				if ($v['fabric_warehouse_sj'] == '' && strtotime($v['fabric_warehouse_yq']) < time()) {
					$state = '面料到仓已超期';
				}
				if($v['product_sample_sj'] == '' && strtotime($v['product_sample_yq']) < time()) {
					$state = '产前样已超期';
				}
				if($v['product_sample_opinion_sj'] == '' && strtotime($v['product_sample_opinion_yq']) < time()) {
					$state = '产前样意见已超期';
				}
				if($v['cut_off_sj'] == '' && strtotime($v['cut_off_yq']) < time()) {
					$state = '开裁已超期';
				}
				if($v['go_online_sj'] == '' && strtotime($v['go_online_yq']) < time()) {
					$state = '上线已超期';
				}
				if($v['finishing_sj'] == '' && strtotime($v['finishing_yq']) < time()) {
					$state = '后整已超期';
				}
				if($v['inspection_sj'] == '' && strtotime($v['inspection_yq']) < time()) {
					$state = '验货已超期';
				}
				if($v['shipment_sj'] == '' && strtotime($v['shipment_yq']) < time()) {
					$state = '出货已超期';
				}else if($v['shipment_sj'] != ''){
					$state = '';
				}
				
				if(empty($state)){
					//订单正常，跳过
					continue;
				}
				
				$overdue_order .= "<br />&emsp;&emsp;&emsp;&emsp;订单号：{$v['order_no']}，款号：{$v['style_no']}，{$state}";
			}
			
//			$email_list[]['name'] = $va['name'];
//			$email_list[]['overdue'] = $overdue_order;
//			var_dump($overdue_order);exit;
//			continue;
			
			if(empty($overdue_order)){
				//无超期订单
				continue;
			}
			
			//是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
			$mail->SMTPDebug = 0;
			// 使用smtp鉴权方式发送邮件
			$mail->isSMTP();
			// smtp需要鉴权 这个必须是true
			$mail->SMTPAuth = true;
			// 链接qq域名邮箱的服务器地址
			$mail->Host = 'smtp.qq.com';
			// 设置使用ssl加密方式登录鉴权
			$mail->SMTPSecure = 'ssl';
			// 设置ssl连接smtp服务器的远程服务器端口号
			$mail->Port = 465;
			// 设置发送的邮件的编码
			$mail->CharSet = 'UTF-8';
			// 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
			$mail->FromName = '思科迪';
			// smtp登录的账号 QQ邮箱即可
			$mail->Username = '1918122910@qq.com';//1918122910@qq.com
			// smtp登录的密码 使用生成的授权码
			$mail->Password = 'behxdhswsmvfefgh';//   sawzsllcioxgcaef  behxdhswsmvfefgh
			// 设置发件人邮箱地址 同登录账号
			$mail->From = '1918122910@qq.com';//1918122910@qq.com
			// 邮件正文是否为html编码 注意此处是一个方法
			$mail->isHTML(true);
			
			//发送到邮箱
			$mail->addAddress($va['email']);
			// 添加该邮件的主题
			$mail->Subject = '订单超期';
			// 添加邮件正文
			$desc = "<h3>{$va['name']}、{$va['email']}、超期订单：{$overdue_order}<br/>请尽快处理！</h3>";
			$mail->Body = $desc;
			// 为该邮件添加附件
			$status = $mail->send();
			if($status){
				$sending_num++;
			}
		}
		exit('123456');
		var_dump($email_list);exit;
		//新增调用记录
		$csll_desc = '发送邮件次数：' .$sending_num;
		$sql = "insert into calls(`title`, `desc`, `type`, `create_time`) values ('订单超期邮件提醒', '{$csll_desc}', 1, now())";
		db::insert($sql);
	}
	
	/**
	 * 订单超期提醒
	 * @login 订单超期(时间节点)  周一、周三早上9点给业务员、跟单员  发送邮件
	 *  实际时间未填写并且当前时间大于预期时间，发送邮件提醒
	实际时间有填写，不发送邮件
	 */
	public function overdue_remind(){
		//获取用户
		$sql = "select `Id`, `email`, `name`
						from users
						where state=1 and email!=''";
		$user_list = json_decode(json_encode(db::select($sql)),true);
		
		//发送邮件
		$sending_num = 0;
		$mail = new \App\Libs\PHPMailer\src\PHPMailer();//实例化邮箱
		foreach ($user_list as $ka=>$va){
			//用户相关订单
			$sql = "select od.order_no, od.style_no, odn.*
					from orders_detailed od
					inner join orders_detailed_node odn on odn.detailed_id = od.Id
					where od.file_state=1 and (od.user_yw={$va['Id']} or od.user_gd={$va['Id']})";
			$order_list = json_decode(json_encode(db::select($sql)),true);
			if(empty($order_list)){
				//无相关订单
				continue;
			}
			
			//获取超期订单
			$overdue_order = '';
			foreach ($order_list as $k=>$v){
				//判断是不是超期订单
				$state = '';
				if($v['head_mail_sj'] == '' && strtotime($v['head_mail_yq']) < time()) {
					$state = '头样寄出已超期';
				}else if($v['head_mail_sj'] != ''){
					$state = '';
				}
				if($v['head_time_sj'] == '' && strtotime($v['head_time_yq']) < time()) {
					$state = '头样意见已超期';
				}else if($v['head_time_sj'] != ''){
					$state = '';
				}
				if($v['contract_sj'] == '' && strtotime($v['contract_yq']) < time()) {
					$state = '下合同已超期';
				}else if($v['contract_sj'] != ''){
					$state = '';
				}
				if($v['card_mail_sj'] == '' && strtotime($v['card_mail_yq']) < time()) {
					$state = '色卡寄出已超期';
				}else if($v['card_mail_sj'] != ''){
					$state = '';
				}
				if($v['card_opinion_sj'] == '' && strtotime($v['card_opinion_yq']) < time()) {
					$state = '色卡意见已超期';
				}else if($v['card_opinion_sj'] != ''){
					$state = '';
				}
				if ($v['fabric_warehouse_sj'] == '' && strtotime($v['fabric_warehouse_yq']) < time()) {
					$state = '面料到仓已超期';
				}else if($v['fabric_warehouse_sj'] != ''){
					$state = '';
				}
				if($v['product_sample_sj'] == '' && strtotime($v['product_sample_yq']) < time()) {
					$state = '产前样已超期';
				}else if($v['product_sample_sj'] != ''){
					$state = '';
				}
				if($v['product_sample_opinion_sj'] == '' && strtotime($v['product_sample_opinion_yq']) < time()) {
					$state = '产前样意见已超期';
				}else if($v['product_sample_opinion_sj'] != ''){
					$state = '';
				}
				if($v['cut_off_sj'] == '' && strtotime($v['cut_off_yq']) < time()) {
					$state = '开裁已超期';
				}else if($v['cut_off_sj'] != ''){
					$state = '';
				}
				if($v['go_online_sj'] == '' && strtotime($v['go_online_yq']) < time()) {
					$state = '上线已超期';
				}else if($v['go_online_sj'] != ''){
					$state = '';
				}
				if($v['finishing_sj'] == '' && strtotime($v['finishing_yq']) < time()) {
					$state = '后整已超期';
				}else if($v['finishing_sj'] != ''){
					$state = '';
				}
				if($v['inspection_sj'] == '' && strtotime($v['inspection_yq']) < time()) {
					$state = '验货已超期';
				}else if($v['inspection_sj'] != ''){
					$state = '';
				}
				if($v['shipment_sj'] == '' && strtotime($v['shipment_yq']) < time()) {
					$state = '出货已超期';
				}else if($v['shipment_sj'] != ''){
					$state = '';
				}
				
				if(empty($state)){
					//订单正常，跳过
					continue;
				}
				
				$overdue_order .= "<br />&emsp;&emsp;&emsp;&emsp;订单号：{$v['order_no']}，款号：{$v['style_no']}，{$state}";
			}
			
			if(empty($overdue_order)){
				//无超期订单
				continue;
			}
			
			$arr = array();
			$arr['email'] = $va['email'];
			$arr['body'] = "<h3>{$va['name']}、{$va['email']}、超期订单：{$overdue_order}<br/>请尽快处理！</h3>";
			$return = $this->php_meail($arr);
			if($return){
				$sending_num++;
			}
			
		}
		//新增调用记录
		$csll_desc = '发送邮件次数：' .$sending_num;
		$sql = "insert into calls(`title`, `desc`, `type`, `create_time`) values ('订单超期邮件提醒', '{$csll_desc}', 1, now())";
		db::insert($sql);
	}
	
	//发送邮件
	public function php_meail($data){
		$mail = new \App\Libs\PHPMailer\src\PHPMailer();//实例化邮箱
		//是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
		$mail->SMTPDebug = 0;
		// 使用smtp鉴权方式发送邮件
		$mail->isSMTP();
		// smtp需要鉴权 这个必须是true
		$mail->SMTPAuth = true;
		// 链接qq域名邮箱的服务器地址
		$mail->Host = 'smtp.qq.com';
		// 设置使用ssl加密方式登录鉴权
		$mail->SMTPSecure = 'ssl';
		// 设置ssl连接smtp服务器的远程服务器端口号
		$mail->Port = 465;
		// 设置发送的邮件的编码
		$mail->CharSet = 'UTF-8';
		// 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
		$mail->FromName = '思科迪';
		// smtp登录的账号 QQ邮箱即可
		$mail->Username = '1918122910@qq.com';//1918122910@qq.com
		// smtp登录的密码 使用生成的授权码
		$mail->Password = 'behxdhswsmvfefgh';//   sawzsllcioxgcaef  behxdhswsmvfefgh
		// 设置发件人邮箱地址 同登录账号
		$mail->From = '1918122910@qq.com';//1918122910@qq.com
		// 邮件正文是否为html编码 注意此处是一个方法
		$mail->isHTML(true);
		
		//发送到邮箱
		$mail->addAddress($data['email']);
		// 添加该邮件的主题
		$mail->Subject = '订单超期';
		// 添加邮件正文
		$mail->Body = $data['body'];
		// 为该邮件添加附件
		$status = $mail->send();
		if($status){
			return true;
		}
	}





////////////////////////////////////////////////  任务定时器
	/**
	 * 触发定时器
	 * http://admin.com:84/pc/login/timer_trigger
	 */
	public function timer_trigger(){
		$call_task = new \App\Libs\wrapper\Task();
		$return = $call_task->timer_trigger();
//		var_dump($return);exit;
		
		//0 08 * * * /usr/bin/curl http://new.zity.cn/pc/login/timer_trigger"
		//00 08 * * * /usr/bin/curl "http://new.zity.cn/pc/login/timer_trigger"
		
	}
	





















//
}
